package com.ychs.lawyerback01.controller;

import com.ychs.lawyerback01.annotation.RequirePermission;
import com.ychs.lawyerback01.common.R;
import com.ychs.lawyerback01.common.ResultCode;
import com.ychs.lawyerback01.dto.SealQueryDTO;
import com.ychs.lawyerback01.pojo.SealRecord;
import com.ychs.lawyerback01.service.SealRecordService;

import com.ychs.lawyerback01.util.FileDownloadUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;



import java.io.IOException;

import java.util.Map;

@RestController
@RequestMapping("/seal-records")
public class SealRecordController {

    @Autowired
    private SealRecordService sealRecordService;

    /**
     * 分页查询印章记录
     */
    @RequirePermission("system:seal:list")
    @GetMapping("/list")
    public R<Map<String, Object>> getSealRecordsByPage(
            @ModelAttribute SealQueryDTO queryDTO) {
        try {
            Map<String, Object> result = sealRecordService.getSealRecordsByPage(queryDTO);
            return R.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(ResultCode.ERROR.getCode(), "查询失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取印章记录详情
     */
    @GetMapping("/{id}")
    public R<SealRecord> getSealRecordById(@PathVariable Long id) {
        try {
            SealRecord sealRecord = sealRecordService.getSealRecordById(id);
            if (sealRecord == null) {
                return R.fail(ResultCode.USER_NOT_FOUND);
            }
            return R.success(sealRecord);
        } catch (Exception e) {
            return R.fail(ResultCode.ERROR.getCode(), e.getMessage());
        }
    }

    /**
     * 新增印章记录
     */
    @RequirePermission("system:seal:add")
    @PostMapping
    public R<SealRecord> addSealRecord(
            @RequestBody SealRecord sealRecord,
            @RequestParam String operator) {
        try {
            SealRecord savedRecord = sealRecordService.addSealRecord(sealRecord, operator);
            return R.success(savedRecord);
        } catch (Exception e) {
            return R.fail(ResultCode.ERROR.getCode(), "新增失败: " + e.getMessage());
        }
    }

    /**
     * 更新印章记录
     */
    @RequirePermission("system:seal:update")
    @PutMapping("/{id}")
    public R<SealRecord> updateSealRecord(
            @PathVariable Long id,
            @RequestBody SealRecord sealRecord,
            @RequestParam String operator) {
        try {
            SealRecord updatedRecord = sealRecordService.updateSealRecord(id, sealRecord, operator);
            return R.success(updatedRecord);
        } catch (RuntimeException e) {
            return R.fail(ResultCode.UPDATE_FAILE);
        } catch (Exception e) {
            return R.fail(ResultCode.ERROR.getCode(), "更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除印章记录
     */
    @RequirePermission("system:seal:delete")
    @DeleteMapping("/{id}")
    public R<Void> deleteSealRecord(@PathVariable Long id) {
        try {
            sealRecordService.deleteSealRecord(id);
            return R.success();
        } catch (RuntimeException e) {
            return R.fail(ResultCode.DELETE_FAILE);
        } catch (Exception e) {
            return R.fail(ResultCode.ERROR.getCode(), "删除失败: " + e.getMessage());
        }
    }

    /**
     * 导出印章记录Excel
     */
    @RequirePermission("system:seal:export")
    @GetMapping("/export")
    public void exportExcel(
            @ModelAttribute SealQueryDTO queryDTO,
            HttpServletResponse response) throws IOException {
        try {
            sealRecordService.exportExcel(queryDTO,response);
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出失败: " + e.getMessage());
        }
    }
    @RequirePermission("system:seal:download")
    @GetMapping("/downloadTemplate")
    public void downloadSealTemplate(HttpServletResponse response) {
        try {
            // 关键：直接指定目标文件名（必须与resources/templates下的文件完全一致）
            String targetFileName = "印章使用登记模板.docx";
            // 下载时前端显示的文件名（可与原文件名一致，支持中文）
            String downloadShowName = "印章使用登记模板.docx";
            // 调用工具类，传入固定文件名，下载指定文件
            FileDownloadUtil.downloadTemplate(
                    response,
                    targetFileName, // 后端templates目录下的目标文件名
                    downloadShowName // 前端下载时显示的文件名
            );
        } catch (IOException e) {
            // 异常处理：若文件不存在，返回500错误
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace(); // 控制台打印异常（方便排查文件是否存在）
        }
    }
}
